import { Component, Input, OnInit, ElementRef, Renderer2, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, Platform, ToastController } from 'ionic-angular';
import { TopicInfo } from '../../models/quesinfo';
import { ImagePicker, ImagePickerOptions } from '@ionic-native/image-picker';//照片信息
import { Media, MediaObject } from '@ionic-native/media';//录音
import { File } from '@ionic-native/file';//录音文件
import { ActionSheetController,AlertController } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';//相机
import { DomSanitizer } from '@angular/platform-browser';//解除xxs攻击


declare let BMap;
declare let BMapLib;

@Component({
  selector: 'page-phone-record',
  templateUrl: 'phone-record.html',
})

export class PhoneRecordPage implements OnInit {
  @Input() topic: TopicInfo;
  @Input() poneSet: Array<any>;
  TemResult = 20;
  @ViewChild('recordshow') recordshow: ElementRef;
  @ViewChild('img') img: ElementRef;
  options: CameraOptions = {//相机设置
    quality: 50,
    destinationType: this.camera.DestinationType.DATA_URL,//图片路径
    encodingType: this.camera.EncodingType.JPEG,//图片类型
    mediaType: this.camera.MediaType.PICTURE//媒体类型
  }
  pickerOpts: ImagePickerOptions = {//图片设置
    outputType: 1,//输入类型
    quality: 50,//图片质量
    maximumImagesCount: 1,//最多选择几张图片
  };
  get recordTime(): string {
    const s = this.recordTimes;
    let hours = Math.round((s - 30 * 60) / (60 * 60));
    let _hours = hours < 10 ? ('0' + hours) : hours;
    let minutes = Math.round((s - 30) / 60) % 60;
    let _minutes = minutes < 10 ? ('0' + minutes) : minutes;
    let seconds = s % 60;
    let _seconds = seconds < 10 && seconds >= 1 ? ('0' + seconds) : seconds;
    return (hours > 0 ? (_hours + ":") : "00:") + (minutes > 0 ? (_minutes + ":") : "00:") + (seconds > 0 ? (_seconds + "") : "00");
  }
  province='';
  city='';
  district='';
  bigImagesUrl:boolean=false;//图片放大
  street='';
  streetNumber='';
  lat='';
  longitude='';
  imageData = "";
  filePath = "";
  recordTimes = 0;
  tabimgHandle = 0;
  recordFileName = 'my_file.mp3';
  audioUrl;
  recordCap = '开始录音';
  public recordData: MediaObject; //录音对象
  isHide(type: number): boolean {
    const findR = this.poneSet.filter(e=> e.title===this.topic.typename && ((type===0 && e.isCheckedPhoto)||(type===1 && e.isCheckedAudio))).length;
    if(findR){
      return true;
    }
    return false
  }

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private renderer: Renderer2,
    public toastCtrl: ToastController,
    private imagePicker: ImagePicker,
    private media: Media,
    private file: File,
    private actionSheetCtrl: ActionSheetController,
    private camera: Camera,
    public sanitizer: DomSanitizer,
    public platform: Platform,
    public alertCtrl: AlertController
  ) {
  }
  ngOnInit(): void {
    // let time;
    // time = this.GetTime(this.timeshow);
    // this.nextBtnText = time;

    this.audioUrl = this.sanitizer.bypassSecurityTrustUrl(this.topic.FAudio);
  }

  // 地图

  @ViewChild('mapRecord') map: ElementRef;

  showmap() {
    let el = this.map.nativeElement;
    this.renderer.addClass(el, 'mapmalshow');
    this.ionViewWillEnter();
  }

  saveMap() {
    // alert(document.getElementById('province').innerText);
    // let province = document.getElementById('province').innerText;
    // let city = document.getElementById('city').innerText;
    // let district = document.getElementById('district').innerText;
    // let street = document.getElementById('street').innerText;
    // let streetNumber = document.getElementById('streetNumber').innerText;
    // let lat = document.getElementById('lat').innerText;
    // let longitude = document.getElementById('longitude').innerText;
if(!this.province){
  let confirm = this.alertCtrl.create({
    title: '请选择位置',
    buttons: [
      {

        text: '确定',
        handler: () => {
        }
      }
    ]

  });
  confirm.present();
}else{
  this.topic.Address = this.province + "-" + this.city + "-" + this.district + "-" + this.street + "" + this.streetNumber;
  this.topic.lat = this.lat;
  this.topic.longitude = this.longitude;
  let el = this.map.nativeElement;
  this.renderer.removeClass(el, 'mapmalshow');
}
  }

  cancalMap() {
    let el = this.map.nativeElement;
    this.renderer.removeClass(el, 'mapmalshow');
  }

  ionViewWillEnter() {
    let map = new BMap.Map('map'+this.topic.FTopicId);
    // map.centerAndZoom(new BMap.Point(120.129721,30.314429), 6);
    map.enableContinuousZoom();//连续缩放效果，默认禁用
    map.enableScrollWheelZoom();//启动滚轮放大缩小，默认禁用
    console.log(this.topic);
    let pp = new BMap.Point(this.topic.longitude, this.topic.lat);
    map.centerAndZoom(pp, 14);//设置中心和地图显示级别
    //
    let marker1 = new BMap.Marker(pp);
    map.addOverlay(marker1);

    let geoc = new BMap.Geocoder();
    var temp;
    const $this = this;
    map.addEventListener("click", function (e) {
      map.removeOverlay(marker1);
      pp.lng = e.point.lng;
      pp.lat = e.point.lat;
      marker1 = new BMap.Marker(pp);
      map.addOverlay(marker1);

      let pt = e.point;
      geoc.getLocation(pt, function (rs) {
        let addComp = rs.addressComponents;
        // temp=addComp.longitude;
        $this.province = addComp.province;
        $this.city = addComp.city;
        $this.district = addComp.district;
        $this.street = addComp.street;
        $this.streetNumber = addComp.streetNumber;
        $this.lat = pp.lat;
       
        $this.longitude = pp.lng;
        // document.getElementById('province').innerText = addComp.province;
        // document.getElementById('city').innerText = addComp.city;
        // document.getElementById('district').innerText = addComp.district;
        // document.getElementById('street').innerText = addComp.street;
        // document.getElementById('streetNumber').innerText = addComp.streetNumber;
        // document.getElementById('lat').innerText = pp.lat;
        // document.getElementById('longitude').innerText = pp.lng;
      });
    })
  };

  /**
   * 图片
   */
  clg() {
    const actionSheet = this.actionSheetCtrl.create({
      title: '图片来源',
      buttons: [
        {
          text: '拍摄',
          handler: () => {
            this.camera.getPicture(this.options).then((imageData) => {
              this.topic.FImage = 'data:image/jpeg;base64,' + imageData;
            }, (err) => {
              // Handle error
            });
          }
        }, {
          text: '相册',
          handler: async () => {
            const isCan = await this.imagePicker.hasReadPermission();//判断是否有读取权限 (android用)
            if (!isCan) {
              await this.imagePicker.requestReadPermission();//请求读取权限 (android用)
            }
            this.imagePicker.getPictures(this.pickerOpts).then((results) => {
              for (var i = 0; i < results.length; i++) {
                this.topic.FImage = 'data:image/jpeg;base64,' + results[i];
                break;
              }
            }, (err) => { });
          }
        }
      ]
    });
    actionSheet.present();
  }


  record() {
    let el = this.recordshow.nativeElement;
    this.renderer.addClass(el, 'show');
    // this.topic.FAudio = "audio";
  }



  /**
   * 录音
   */
  tabimg() {
    if (!this.recordTimes) {

      if (this.platform.is('ios')) {
        this.recordFileName = new Date().getTime() + 'my_file.wav';
        this.filePath = this.file.tempDirectory.replace(/^file:\/\//, '') + this.recordFileName;
        // alert(this.filePath);
      }
      else {
        this.recordFileName = new Date().getTime() + 'my_file.mp3';
        this.filePath = this.file.externalDataDirectory + this.recordFileName;
      }

      this.recordData = this.media.create(this.filePath);
      this.recordData.startRecord();//开始录制音频文件
      this.recordCap = "正在录音";
      this.tabimgHandle = window.setInterval(() => {
        this.recordTimes += 1;
      }, 1000);
    } else if (this.recordTimes > 0) {
      if (this.recordCap === "正在录音") {
        this.recordCap = "点击继续";
        this.recordData.pauseRecord();//音频文件暂停录音
        window.clearInterval(this.tabimgHandle);
      } else {
        this.recordCap = "正在录音";
        this.recordData.resumeRecord();//恢复音频文件记录
        this.tabimgHandle = window.setInterval(() => {
          this.recordTimes += 1;
        }, 1000);
      }

    }
    // let el = this.img.nativeElement;
    // this.renderer.setAttribute(el, 'src', '')
  }
  cancle() {
    if (this.recordData) {
      this.recordData.stopRecord();//停止录制音频文件
      this.recordData.release();//释放操作系统底层的音频资源
    }

    this.recordTimes = 0;
    this.recordCap = "开始录音";
    // 样式修改
    window.clearInterval(this.tabimgHandle);
    let el = this.recordshow.nativeElement;
    this.renderer.removeClass(el, 'show');
  }
  async save() {
    if (this.recordData) {
      this.recordData.stopRecord();//停止录制音频文件
      window.clearInterval(this.tabimgHandle);
    }
    if (this.recordData) {
      // 开始保存文件

      let file;
      if (this.platform.is('ios')) {
        file = this.file.tempDirectory;
      } else {
        file = this.file.externalDataDirectory;
      }
      let results;
      try {
        results = await this.file.readAsDataURL(file, this.recordFileName);
      }
      catch (e) {
        // alert(JSON.stringify(e));
      }

      this.topic.FAudio = results;
      this.audioUrl = this.sanitizer.bypassSecurityTrustUrl(results);
      this.topic.FAudioLength = this.recordTimes;

      this.recordData.release();
      this.recordTimes = 0;
      this.recordCap = "开始录音";

      let el = this.recordshow.nativeElement;
      this.renderer.removeClass(el, 'show');
      let toast = this.toastCtrl.create({
        message: "保存成功！",
        duration: 3000,
        position: 'bottom'
      });
      toast.present();
      return false;
    }
  }

  cleanImg() {
    this.topic.FImage = '';
  }
  cleanAudio() {
    this.topic.FAudio = '';
    this.topic.FAudioLength = 0;
    this.audioUrl = null;
  }
  bigpic(){
    this.bigImagesUrl=true;
  }
  hideBigImage(){
    this.bigImagesUrl=false;
  }
}
